package com.jiahao.material.controllers;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jiahao.material.entity.Material;
import com.jiahao.material.entity.Permission;
import com.jiahao.material.entity.Result;
import com.jiahao.material.entity.Role;
import com.jiahao.material.entity.WarehouseMaterial;
import com.jiahao.material.mapper.WarehouseMaterialMapper;
import com.jiahao.material.services.IMaterialService;
import com.jiahao.material.services.IRoleService;
import com.jiahao.material.services.IWarehouseMaterialService;
import com.jiahao.material.utils.ResultUtil;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@CrossOrigin
@RestController
@RequestMapping("/material")
public class MaterialController {

    @Autowired
    private IMaterialService materialService;

    @Autowired
    private IWarehouseMaterialService warehouseMaterialService;

    @RequiresPermissions("addMaterial")
    @PostMapping("/add")
    public Result add(@RequestBody Material material) throws Exception{
        //check
        QueryWrapper<Material> materialQueryWrapper = new QueryWrapper<>();
        materialQueryWrapper.eq("name",material.getName());
        List<Material> list = materialService.list(materialQueryWrapper);
        if (list!=null && list.size()>0){
            return ResultUtil.fail("该材料已存在!");
        }

        material.setStatus("01");
        materialService.save(material);
        return ResultUtil.success("添加材料成功!");
    }

    @PostMapping("/page")
    public Result getByPage(@RequestBody Map<String,Object> map) throws Exception{
        int pageSize = map.get("pageSize") == null ? 10 : Integer.parseInt(map.get("pageSize").toString());
        int currentPage = map.get("currentPage") == null ? 1 : Integer.parseInt(map.get("currentPage").toString());
        Page<Material> page = new Page<>(currentPage,pageSize);

        QueryWrapper<Material> materialQueryWrapper = new QueryWrapper<>();

        //根据需求添加查询条件
        if (map.get("name")!=null && !map.get("name").toString().equals("")){
            materialQueryWrapper.like("name",map.get("name").toString());
        }

        if (map.get("type")!=null && !map.get("type").toString().equals("")){
            materialQueryWrapper.eq("type",map.get("type").toString());
        }

        if (map.get("status")!=null && !map.get("status").toString().equals("")){
            materialQueryWrapper.eq("status",map.get("status").toString());
        }


        IPage<Material> page1 = materialService.page(page, materialQueryWrapper);
        return ResultUtil.success("",page1);
    }


    @GetMapping("/byId/{id}")
    public Result getById(@PathVariable String id) throws Exception{
        Material byId = materialService.getById(id);
        return ResultUtil.success("",byId);
    }

    @GetMapping("/all")
    public Result getAll() throws Exception{
        List<Material> list = materialService.list();
        return ResultUtil.success("",list);
    }

    @GetMapping("/activeAll")
    public Result getActiveAll() throws Exception{
        QueryWrapper<Material> materialQueryWrapper = new QueryWrapper<Material>();
        materialQueryWrapper.eq("status","01");
        List<Material> list = materialService.list(materialQueryWrapper);
        return ResultUtil.success("",list);
    }

    @RequiresPermissions("updateMaterial")
    @PutMapping("/update")
    public Result update(@RequestBody Material material) throws Exception{
        //check
        QueryWrapper<Material> materialQueryWrapper = new QueryWrapper<>();
        materialQueryWrapper.eq("name",material.getName());
        List<Material> list = materialService.list(materialQueryWrapper);
        if (list!=null && list.size()>0){
            if (list.get(0).getId().equals(material.getId())){
                return ResultUtil.fail("该材料已存在!");
            }
        }


        materialService.updateById(material);
        return ResultUtil.success("更新材料成功!");
    }

    /**
     * 更新状态
     * @param map
     * @return
     * @throws Exception
     */
    @RequiresPermissions("updateMaterial")
    @PutMapping("/status")
    @Transactional
    public Result updateStatus(@RequestBody Map<String,Object> map) throws Exception{
        UpdateWrapper<Material> materialUpdateWrapper = new UpdateWrapper<>();
        materialUpdateWrapper.eq("id",map.get("id").toString()).set("status",map.get("status").toString());
        materialService.update(materialUpdateWrapper);
        return ResultUtil.success("更新状态成功!");
    }

    @RequiresPermissions("delMaterial")
    @DeleteMapping("/del/{id}")
    public Result delById(@PathVariable String id) throws Exception{
        //检查仓库是否有商品信息,有的话不删除
        QueryWrapper<WarehouseMaterial> warehouseMaterialQueryWrapper = new QueryWrapper<>();
        warehouseMaterialQueryWrapper.eq("mid",id);
        int count = warehouseMaterialService.count(warehouseMaterialQueryWrapper);
        if (count>0){
            return ResultUtil.fail("材料被使用,禁止删除");
        }

        materialService.removeById(id);
        return ResultUtil.success("删除材料成功!");
    }

    @RequiresPermissions("delMaterial")
    @PostMapping("/dels")
    public Result delByIds(@RequestBody List<String> ids) throws Exception{
        //检查仓库是否有商品信息,有的话不删除
        QueryWrapper<WarehouseMaterial> warehouseMaterialQueryWrapper = new QueryWrapper<>();
        warehouseMaterialQueryWrapper.in(true,"mid",ids);
        int count = warehouseMaterialService.count(warehouseMaterialQueryWrapper);
        if (count>0){
            return ResultUtil.fail("材料被使用,禁止删除");
        }

        materialService.removeByIds(ids);
        return ResultUtil.success("删除材料成功!");
    }

    /**
     * 上传头像
     * @param file
     * @return
     * @throws Exception
     */
    @PostMapping("/images")
    public Result uploadIcon(@RequestBody MultipartFile file) throws Exception{
        if (file.isEmpty()){
            return null;
        }
        String originName=file.getOriginalFilename();
        String suffixName = originName.substring(originName.lastIndexOf("."));  // 后缀名
        String filePath = ClassUtils.getDefaultClassLoader().getResource("").getPath()+"static/images"; // 上传后的路径
        String fileName= UUID.randomUUID().toString().replaceAll("-","")+suffixName;
        File file1=new File(filePath,fileName);
        if (!file1.getParentFile().exists()){
            file1.getParentFile().mkdirs();
        }
        try {
            file.transferTo(file1);
            String url="http://127.0.0.1:8090/images/"+fileName;
            return ResultUtil.success(url);
        } catch (IOException e) {
            e.printStackTrace();
            throw e;
        }
    }

}
